package com.wcgksoft.controller.system;


import com.wcgksoft.common.util.Layui;
import com.wcgksoft.entity.system.SysMenu;
import com.wcgksoft.service.SysMenuService;
import net.sf.json.JSONObject;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * 菜单管理
 *
 * @author x1c
 */
@Controller
@RequestMapping("menu")
public class MenuController {
    @Resource
    private SysMenuService sysMenuService;


    /**
     * 初始化列表页面layui的table加载数据
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "myFindAll", method = RequestMethod.GET)
    public Layui myFindAll() {
        DetachedCriteria detachedCriteria = DetachedCriteria.forClass(SysMenu.class);
        detachedCriteria.addOrder(Order.asc("orderNumber"));
        List<SysMenu> list = sysMenuService.findByConditions(detachedCriteria);//findAll(ItemInfo.class);
        return Layui.data(0, "查询成功", sysMenuService.getTotalCount(), list);
    }

    /**
     * 添加或者修改信息的方法
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "update", method = RequestMethod.POST)
    public Layui update(ModelMap modelMap,
                        @RequestParam(value = "data", required = false) String data) {
        JSONObject param = JSONObject.fromObject(data);
        if (param == null) {
            return Layui.data(1, "请求格式有误", 0, null);
        } else {
            SysMenu sysMenu = (SysMenu) JSONObject.toBean(JSONObject.fromObject(data), SysMenu.class);
            Integer lx = param.getInt("lx");
            sysMenu.setIsMenu(lx);
            Integer ldkj = param.getInt("ldkj");
            sysMenu.setIsLeader(ldkj);
            String parentIds = String.valueOf(param.get("pid"));
            if (parentIds.equals("")) {
                sysMenu.setParentId(-1);
            } else {
                Integer parentId = Integer.parseInt(parentIds);
                sysMenu.setParentId(parentId);
            }

            if (null == sysMenu.getId()) {
                sysMenu.setCreateTime(new Date());
            } else {
                sysMenu.setUpdateTime(new Date());
            }
            sysMenuService.saveOrUpdate(sysMenu);
            return Layui.data(0, "菜单信息更新成功", 1, Layui.addList(sysMenu));
        }
    }


    /**
     * 根据id删除
     * @param id
     * @param
     * @return
     */
    @RequestMapping(value="delete")
    @ResponseBody
    public Layui delete(@RequestParam(value = "id") String id){
        sysMenuService.deleteAll("SysMenu", id);
        return Layui.data(1,"删除功能",1,null);
    }
}
